package com.gzz.orchid.main.facade.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/api/stock")
public class EmitterController {
    private final Map<String, ResponseBodyEmitter> emitters = new ConcurrentHashMap<>();

    @GetMapping("/subscribe/{symbol}")
    public ResponseBodyEmitter subscribe(@PathVariable String symbol) {
        ResponseBodyEmitter emitter = new ResponseBodyEmitter(30000L);
        // 保存发射器以便后续推送数据
        emitters.put(symbol, emitter);
        // 模拟实时行情更新
        Executors.newSingleThreadExecutor().execute(() -> {
            try {
                while (true) {
                    double price = Math.random() * 100; // 随机生成股价
                    emitter.send("{\"symbol\":\"" + symbol + "\",\"price\":" + price + "}");
                    Thread.sleep(5000); // 每5秒更新一次
                }
            } catch (Exception e) {
                emitter.completeWithError(e);
                emitters.remove(symbol);
            }
        });
        return emitter;
    }

    // 推送消息给所有订阅者
    public void pushStockUpdate(String symbol, double price) {
        ResponseBodyEmitter emitter = emitters.get(symbol);
        if (emitter != null) {
            try {
                emitter.send("{\"symbol\":\"" + symbol + "\",\"price\":" + price + "}");
            } catch (Exception e) {
                emitter.completeWithError(e);
                emitters.remove(symbol);
            }
        }
    }

    /**
     * 前端效果：文字像打字机一样逐字出现，用户体验更自然
     */
    @GetMapping("/chat")
    public ResponseBodyEmitter chatWithAi() {
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        Executors.newSingleThreadExecutor().execute(() -> {
            try {
                String[] aiResponse = {
                        "你好！我是AI助手。",
                        "今天有什么可以帮你的？",
                        "我可以回答问题、提供建议，或者陪你聊天。"
                };
                for (String message : aiResponse) {
                    Thread.sleep(1000); // 模拟AI思考时间
                    emitter.send(message);
                }
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }
}
